package com.hmall.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.dto.PageDTO;
import com.hmall.item.dto.ItemAddDTO;
import com.hmall.item.mapper.ItemMapper;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.IItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Date;

@Service
public class ItemService extends ServiceImpl<ItemMapper, Item> implements IItemService {
    @Autowired
    ItemMapper itemMapper;
    /**
     * 分页查询商品
     * */
    @Override
    public PageDTO<Item> findByPage(Integer page, Integer size) {
        IPage<Item> pages = new Page<>(page, size);
        IPage<Item> result = itemMapper.selectPage(pages, null);
        return new PageDTO<>(result.getTotal(), result.getRecords());
    }
    /**
     * 新增商品
     * */
    @Override
    public void add(ItemAddDTO dto) {
        dto.setStatus(1);
        dto.setCategory(String.valueOf(LocalDateTime.now()));
        itemMapper.insert(dto);
    }

    /**
     * 上架下架商品
     * */
    @Override
    public void updateStatus(Long id, Integer status) {
        Item item = new Item();
        item.setId(id);
        item.setStatus(status);
        itemMapper.updateById(item);
    }

    /**
     * 修改商品
     * */
    @Override
    public void updateItem(ItemAddDTO dto) {
        UpdateWrapper<Item> wrapper = new UpdateWrapper<>();
        Date currentDate = new Date();
        wrapper.eq("id", dto.getId());
        dto.setUpdateTime(currentDate);
        itemMapper.update(dto, wrapper);
    }
    /**
     * 扣减库存
     * */
    @Transactional
    @Override
    public void deductStock(Long itemId, Integer num) {
        //扣减库存
        try{
            update().setSql("stock = stock - "+ num).eq("id",itemId).update();
        } catch (Exception e){
          throw new RuntimeException("库存不足");
        }

    }
}
